package m.jclecai.com.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.BankBean;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.StringUtils;
import m.jclecai.com.view.rounded.RoundedImageView;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import rx.functions.Action1;

public class AccountInfoActivity extends BaseActivity {

    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_card)
    TextView tvCard;
    @BindView(R.id.tv_bank)
    TextView tvBank;
    @BindView(R.id.iv_icon)
    RoundedImageView ivIcon;
    UserBean userBean;

    @BindView(R.id.tv_kefu_number)
    TextView mTvKeFuNumber;
    @BindView(R.id.tv_kefu_qq_number)
    TextView mTvKeFuQQNumber;

    @BindView(R.id.ll_username_and_pwd)
    LinearLayout mLlUsernameAndPwd;

    @BindView(R.id.tv_username)
    TextView mTvUsername;

    @BindView(R.id.tv_invitecode)
    TextView mTvInvitecode;

    @BindView(R.id.tv_alipay)
    TextView mTvAlipay;

    @BindView(R.id.ll_server)
    View mServce;

//    @BindView(R.id.ll_kefu)
//    View mKeFu;





    @BindView(R.id.ll_center_message)
    LinearLayout mLlCenterMessage;

    @Override
    public int getContentView() {
        return R.layout.activity_account_info;
    }

    @Override
    public void initView() {
        super.initView();
        setTitle("我的账户");
        leftOptionText("");

        if (!TextUtils.isEmpty(PreferenceUtil.readString(this,PreferenceUtil.KF_NUMBER,""))) {

            mTvKeFuNumber.setText("客服电话: "+PreferenceUtil.readString(this,PreferenceUtil.KF_NUMBER,""));
            mServce.setVisibility(View.VISIBLE);
        }else{
            mServce.setVisibility(View.GONE);
        }

//
//        if (!TextUtils.isEmpty(PreferenceUtil.readString(this,PreferenceUtil.KF_QQ_NUMBER,""))) {
//            mTvKeFuQQNumber.setText("QQ客服: "+PreferenceUtil.readString(this,PreferenceUtil.KF_QQ_NUMBER,""));
//            mKeFu.setVisibility(View.VISIBLE);
//        }else{
//            mKeFu.setVisibility(View.GONE);
//        }



    }

    @Override
    protected void onResume() {
        super.onResume();
        showUserInfo();
    }

    void showUserInfo() {
        userBean = PreferenceUtil.readUser(this);

        mTvInvitecode.setText(userBean.getInvite_code()+"");

        //这里还需要读取邀请码信息；
        if (userBean != null){
            if (!TextUtils.isEmpty(userBean.getPhone()))
                tvPhone.setText(BaseUtils.formatPhone(userBean.getPhone()));
            if (!TextUtils.isEmpty(userBean.getIdcard())) {
                tvCard.setText("已绑定");
            }

            Glide.with(this)
                    .load(userBean.getUser_face())
                    .asBitmap()
                    .placeholder(R.drawable.my_head_de)
                    .error(R.drawable.my_head_de)
                    .into(ivIcon);
        }
        //设置银行卡的部分；
        BankBean bankBean = PreferenceUtil.getDefaultWithDrawBank(this);
        if (bankBean != null) {
            if(TextUtils.isEmpty(bankBean.getBankno())){
                tvBank.setText("绑定银行卡快速提现");
            }else{
                tvBank.setText("");
                tvBank.append(bankBean.getBank());
                tvBank.append("  (尾号:" + StringUtils.formatBank(bankBean.getBankno()) + ")");
            }
        } else {
            tvBank.setText("绑定银行卡快速提现");
        }

        //设置用户名的那些；
        if(PreferenceUtil.readBoolean(this,PreferenceUtil.IS_USER_NAME_EMPTY,false)){
            mTvUsername.setText("未绑定");
        }else{
            //这里我们要做的一个操作就是；
            if (TextUtils.isEmpty(PreferenceUtil.getUserName(this))) {
                mTvUsername.setText("未绑定");
            }else{
                mTvUsername.setText(PreferenceUtil.getUserName(this));
            }
        }

        String inviteCode = PreferenceUtil.readString(this, PreferenceUtil.INVITE_CODE, "");
        if(inviteCode!=null){
            mTvInvitecode.setText(inviteCode);
        }
        //这里设置支付宝账号；

        if (!TextUtils.isEmpty(userBean.getAlipay())) {

            mTvAlipay.setText(StringUtils.formatBank(userBean.getAlipay()));
        }else{
            mTvAlipay.setText("未绑定");
        }
    }

    @OnClick(R.id.ll_phone)
    void bindPhone() {
        startActivity(new Intent(this, BindPhoneActivity.class));
    }


    @OnClick(R.id.ll_username_and_pwd)
    void resetUsernameAndPwd() {
        if(PreferenceUtil.readBoolean(this,PreferenceUtil.IS_USER_NAME_EMPTY,false)){
            HashMap<String,String> map = new HashMap<>();
            map.put("user",PreferenceUtil.getUserName(this));
            map.put("password",PreferenceUtil.getPassword(this));
            //.putExtra("param", JSON.toJSONString(threeLoginPairmsMap)
            Intent intent = RegisterActivity.getIntent(this, false);
            intent.putExtra("param", JSON.toJSONString(map));
            //这里是需要nickname,password的
            startActivity(intent);
        }
    }


    @OnClick(R.id.ll_bind_alipay)
    public void onClickBindAlipay(){
        //这里是绑定支付宝；
        startActivity(new Intent(this,BindAlipayActivity.class));
    }


    @OnClick(R.id.ll_invitecode)
    public void onClickInviteCode(){
        startActivity(new Intent(this,AddInviteCodeActivity.class));
    }

    @OnClick(R.id.ll_card)
    void bindCard() {
        startActivity(new Intent(this, BindIDCardActivity.class));
    }

    @OnClick(R.id.ll_bank_card)
    void bindBank() {
        startActivity(new Intent(this, BankCardListActivity.class));
    }

    @OnClick(R.id.ll_pwd)
    void updatePwd() {
        startActivityForResult(new Intent(this, UpdatePwdActivity.class),
                Constant_Result.CLEARALLUSERDATA);
    }

    @OnClick(R.id.ll_center_message)
    void onClickCenterMessage() {
        //这里面的话， 我们就显示的消息中心；
        startActivity(new Intent(this,CenterMessageActivity.class));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant_Result.CLEARALLUSERDATA) {
            setResult(resultCode);
            if(resultCode == RESULT_OK)
            finish();
        }else if (requestCode == Constant_Result.REQUESTIMAGE && resultCode == RESULT_OK) {
            /**
             * 处理本地图片
             */
            Log.d(TAG, "onActivityResult() called with: resultCode = [" + resultCode + "], data = [" + data + "]");
            // 获取返回的图片列表
            List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            showThumbImg(path.get(0));
        }
    }

    /**
     * 因为缩略图生成比较慢，所以延时200ms显示
     * 避免由于特殊情况 缩略图获取失败则使用imageloader加载
     * @param url
     */
    void showThumbImg(final String url){
        userBean.setUser_face(url);
        PreferenceUtil.writeUser(this,userBean);

        Glide.with(this)
                .load(url)
                .asBitmap()
                .placeholder(R.drawable.my_head_de)
                .error(R.drawable.my_head_de)
                .into(ivIcon);
    }


    @OnClick(R.id.ll_notice)
    void notice() {
        startActivity(new Intent(this, WebHelperActivity.class)
                .putExtra("title", "公告")
                .putExtra("allowBodyCoverTitle", true)
                .putExtra("code", "http://m.yuecp.net/#type=url&p=user/notice.html"));
    }

    @OnClick(R.id.ll_kefu)
    void onClickQQKefu() {
        //这里我们跳转qq的操作；
        if(isQQClientAvailable(this)){
            String url = "mqqwpa://im/chat?chat_type=wpa&uin="+PreferenceUtil.readString(this,PreferenceUtil.KF_QQ_NUMBER,"");
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        }else{
            DisPlay("没有检测到qq客户端!!!");
        }
    }

    /**
     * 客服电话
     */
    @OnClick(R.id.ll_server)
    void ServicePhone() {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:"+PreferenceUtil.readString(this,PreferenceUtil.KF_NUMBER,"")));
        startActivity(intent);
    }

    /**
     * 判断qq是否可用
     *
     * @param context
     * @return
     */
    public  boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

    @OnClick(R.id.ll_user)
    void openAlbum() {
        RxPermissions rxPermissions = new RxPermissions(this); // where this is an Activity instance
        rxPermissions.request(Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        /**选择拍照**/
                        Intent intent = new Intent(AccountInfoActivity.this, MultiImageSelectorActivity.class);
                        // 是否显示调用相机拍照
                        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, granted);
                        // 最大图片选择数量
                        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
                        // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
                        // intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
                        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                        startActivityForResult(intent, Constant_Result.REQUESTIMAGE);
                    }
                });
    }

}
